#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <linux/i2c-dev.h>

#define BUS_NR 2
#define CHIP_ADDRESS 0x40

int file ;


void write_reg(__u8 add, __u8 val){
    char buf[10];
    buf[0] = add;
    buf[1] = val;
    int chip_addr = CHIP_ADDRESS; /* The I2C address */	
    if (ioctl(file, I2C_SLAVE, chip_addr) < 0) {
        /* ERROR HANDLING; you can check errno to see what went wrong */
        exit(1);
    }
	  if (write(file, buf, 2) != 2) {
	    /* ERROR HANDLING: i2c transaction failed */
  	}
}

void set_led_brightness(__u8 nbr, __u8 bright){
  write_reg(nbr + 2, bright);
}


void set_bright_and_blink(){
  write_reg(0x0C, 0xFF);
  write_reg(0x0D, 0xFF);
}

void init_chip(int nb, __u8 addr){
  char filename[20];	  
  snprintf(filename, 19, "/dev/i2c-%d", nb);
  file = open(filename, O_RDWR);
  if (file < 0) {
  /* ERROR HANDLING; you can check errno to see what went wrong */
    exit(1);
  }
  write_reg(0x00, 0x00);
}

int main(void){
  int pid ;
  __u8 pi = 3 ;
  __u8 ci = 7 ;
  int inc = -1 ;
  __u8 rgb_pi = 0 ;
  __u8 rgb_ci = 2 ;
  int rgb_inc = -1 ;
  init_chip(2, CHIP_ADDRESS);
  set_bright_and_blink();
  pid = fork();
  if(pid != 0){
   return 0 ;
  }
  while(1){
    set_led_brightness(pi, 0x00);
    set_led_brightness(ci, 0xF0);
    set_led_brightness(rgb_pi, 0x00);
    set_led_brightness(rgb_ci, 0x50);
    pi = ci ;
    ci = ci + inc ;
    rgb_pi = rgb_ci ;
    rgb_ci = rgb_ci + rgb_inc ;
    if(ci <= 3 || ci >= 7){
      inc = - inc ;
    }
    if(rgb_ci <= 0 || rgb_ci >= 2){
      rgb_inc = - rgb_inc ;
    }
    usleep(100000);
  }

}
